import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Product } from './product'

export interface CartItem {
  id: number
  product: Product
  quantity: number
  selected: boolean
}

export const useCartStore = defineStore('cart', () => {
  // 购物车商品列表
  const items = ref<CartItem[]>([])

  // 计算属性
  const totalCount = computed(() => 
    items.value.reduce((total, item) => total + item.quantity, 0)
  )

  const selectedItems = computed(() => 
    items.value.filter(item => item.selected)
  )

  const selectedCount = computed(() => 
    selectedItems.value.reduce((total, item) => total + item.quantity, 0)
  )

  const totalPrice = computed(() => 
    selectedItems.value.reduce((total, item) => 
      total + item.product.price * item.quantity, 0
    )
  )

  // 方法
  const addToCart = (product: Product, quantity: number = 1) => {
    const existingItem = items.value.find(item => item.product.id === product.id)
    
    if (existingItem) {
      existingItem.quantity += quantity
    } else {
      items.value.push({
        id: Date.now(),
        product,
        quantity,
        selected: true
      })
    }
  }

  const removeFromCart = (itemId: number) => {
    const index = items.value.findIndex(item => item.id === itemId)
    if (index > -1) {
      items.value.splice(index, 1)
    }
  }

  const updateQuantity = (itemId: number, quantity: number) => {
    const item = items.value.find(item => item.id === itemId)
    if (item) {
      if (quantity <= 0) {
        removeFromCart(itemId)
      } else {
        item.quantity = quantity
      }
    }
  }

  const toggleSelect = (itemId: number) => {
    const item = items.value.find(item => item.id === itemId)
    if (item) {
      item.selected = !item.selected
    }
  }

  const selectAll = (selected: boolean) => {
    items.value.forEach(item => {
      item.selected = selected
    })
  }

  const clearCart = () => {
    items.value = []
  }

  const clearSelected = () => {
    items.value = items.value.filter(item => !item.selected)
  }

  const cartCount = computed(() => items.value)

  return {
    items,
    totalCount,
    selectedItems,
    selectedCount,
    totalPrice,
    addToCart,
    removeFromCart,
    updateQuantity,
    toggleSelect,
    selectAll,
    clearCart,
    clearSelected,
    cartCount,
  }
})